package cn.sciento.starter.sms.service;

import cn.sciento.core.exception.CommonException;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import cn.sciento.starter.sms.configuration.SmsConfigProperties;
import cn.sciento.starter.sms.entity.SmsConfig;
import cn.sciento.starter.sms.entity.SmsMessage;
import cn.sciento.starter.sms.entity.SmsReceiver;
import cn.sciento.starter.sms.exception.SendMessageException;
import cn.sciento.starter.sms.support.AliyunSmsSupporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class AliyunSmsServiceImpl extends SmsService {
  private static final String OK = "OK";
  
  private final SmsConfigProperties configProperties;
  
  private final ObjectMapper objectMapper;
  
  @Autowired
  public AliyunSmsServiceImpl(SmsConfigProperties configProperties, ObjectMapper objectMapper) {
    this.configProperties = configProperties;
    this.objectMapper = objectMapper;
  }
  
  public String serverType() {
    return "ALIYUN";
  }
  
  public void smsSend(List<SmsReceiver> receiverAddressList, SmsConfig smsConfig, SmsMessage message, Map<String, String> args) {
    List<String> telephoneList;
    if (this.configProperties.getSms().isFakeAction() && StringUtils.hasText(this.configProperties.getSms().getFakeAccount())) {
      telephoneList = Collections.singletonList(this.configProperties.getSms().getFakeIdd()
          .replace("+", "00") + this.configProperties.getSms().getFakeAccount());
    } else {
      if (this.configProperties.getSms().isFakeAction()) {
        return;
      }
      telephoneList = receiverAddressList.stream().map(item -> StringUtils.hasText(item.getIdd()) ? (item.getIdd().replace("+", "00") + item.getPhone()) : ("+86".replace("+", "00") + item.getPhone())).collect(Collectors.toList());
    } 
    try {
      SendSmsResponse sendSmsResponse = AliyunSmsSupporter.sendSms(AliyunSmsSupporter.acsClient(smsConfig), smsConfig, message.getExternalCode(), telephoneList, args, this.objectMapper);
      if (sendSmsResponse.getCode() == null || !"OK".equals(sendSmsResponse.getCode())) {
        throw new SendMessageException(this.objectMapper.writeValueAsString(sendSmsResponse));
      }
    } catch (ClientException|com.fasterxml.jackson.core.JsonProcessingException e) {
      throw new CommonException(e);
    } 
  }
}
